const api = require('../../utils/api.js');
const utils = require('../../utils/utils.js');
const app = getApp();
let firstEntry = true;
let _switch = '';

Page({
  data: {
    slide: [],
    notice: [],
    shoplist: [],
    page: 1, //  门店分页
    more: true,
    open_setting: false,
    theme: app.themeData,
    keyword: '',
    hideBtn: true,
    currentInde: 0,
    leng: 0,
    storecate: [],
    abnorData: {
      imgSrc: '/common/static/images/abnor-07.png',
      text: '抱歉！没有相关门店',
    },
    showtype: false,
    _type: 2,
    _typename: '商品',
    param: {
      descending: true,
      cate: '0',
    },
    recommended_stores: '', // 门店列表自定义标题
    list_type: '', // 判断是 门店列表 还是 商品列表
    unit: '',
    play: -1,
    sort: 0,
    imgUrl: app.imgUrl,
    showTabbar: false,
  },

  onLoad(opts) {
    let that = this;
    let options = opts || {};
    let parent_id = 0;
    let share_scene;
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    let userinfo = wx.getStorageSync('user_info');
    // that.entryNearStore();
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    
    if (typeof user_id !== 'undefined') {
      parent_id = user_id;
      share_scene = 4;
    } else if (typeof scene !== 'undefined') {
      parent_id = scene;
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);
    that.setData({
      currentInde: options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex,
      leng: app.siteInfo && app.siteInfo.appJson ? app.siteInfo.appJson.length : 0,
      opts: options,
      visit_platform: options.visit_platform && Number(options.visit_platform) === 1 ? 1 : 0,
      sessionFormStr: JSON.stringify({
        shop_id: 0,
      }),
      parent_id,
      share_scene,
      isBrand: (app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isBrand) || false,
    });
  },
  onShow() {
    let that = this;
    let { opts } = that.data;
    app.ws_micro_shoplogin().then(res => {
      app.util.prepareBindInfo(opts, app.modules, that);
      app.bindGuide(opts);
      let userLocation = wx.getStorageSync('userLocation');
      if (userLocation) {
        that.init(userLocation);
        app.getSetting();
      } else {
        app.getSetting().then(res => {
          that.init(res);
        })
      }
    });
  },
  init(loca = {}) {
    let that = this;
    loca.visit_platform = this.data.visit_platform;
    app.getStoreData(loca).then(res => {
      that.data.store = res.store;

      res.store &&
      res.store.name && 
      wx.setNavigationBarTitle({
        title: res.store.name,
      });
      wx.setStorageSync('latestShopId', res.store.shop_id);
      // let store = wx.getStorageSync('store');
      // that.setData({
      //   store,
      // });
      
      let {
        store: {
          settle_model: settleModel,
          shop_id: settleShopId,
          show_original_price,
          cut_thread
        },
        default_index 
      } = res;
      app.loginBindParent({
        parent_id: that.data.parent_id || 0,
      });
      app.ws_micro_shop_globalData.orgPrice = show_original_price;
      that.entryNearStore(Number(settleModel), Number(settleShopId), default_index);
      if (settleModel !=1) {
        that.loadStoreType();
        utils.judgeUserRole.call(that);
        that.loadStoreHomeData();
        that.loadData();
        app.loadShopSetting().then(res => {

          that.setData({
            cut_thread,
          });
          // that.setData(res);
  
          that.data = Object.assign(that.data, res);
        });
      }
      
    });
  },
  // settleModel 1 开启；0 关闭；-1 其它
  entryNearStore(settleModel = -1, id = '', default_index) {
    let that = this;
    if (settleModel === -1) {
      return false;
    } else if (settleModel === 1) {
      app.ws_micro_shop_globalData.shopid = id;
      app.ws_micro_shop_globalData.settleModel = true;
      app.ws_micro_shop_globalData.fromHome = false;
      app.util.navigateTo('/ws_micro_shop/pages/index/index');
      return false;
    } else if (settleModel === 0) {
      that.loadOneStore(default_index, id);
    } else {
      return false;
    }
  },

  onHide() {
    this.setData({
      play: -1,
    });
  },

  onUnload() {
    this.setData({
      play: -1,
    });
  },

  onPageScroll() {
    let that = this;
    if (Number(that.data.play) !== -1 && that.data.noScrollListen === false) {
      wx.createSelectorQuery()
        .select('.video')
        .fields(
          {
            rect: true,
          },
          function(res) {
            let max = wx.systemInfo.windowHeight;
            if (
              res &&
              res.top &&
              res.top !== null &&
              (res.top <= -200 || res.top >= max - 57)
            ) {
              that.setData({
                play: -1,
              });
            }
          }
        )
        .exec();
    }
  },

  cancelAuth(e) {
    setTimeout(() => {
      wx.hideLoading();
    }, 100);
  },

  loadData() {
    let that = this;
    let { get_coupon_list } = that.data;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.index_new,
      data: {
        type: 'module_list',
        shop_id: 0,
      },
      success: function(res) {
        if (res.code === 0) {
          let indexData = res.data;
          let module_list_arr = [];
          let module_list_arr2 = [];
          if (
            get_coupon_list &&
            get_coupon_list.length &&
            get_coupon_list.length > 0
          ) {
          } else {
            indexData.get_coupon_list = indexData.new_coupon_list;
          }
          indexData.module_list.forEach(function(item, index, arr) {
            module_list_arr.push(item.name);
          });
          that.setData({
            isSearchShow: module_list_arr.includes('search'),
          });
          module_list_arr.forEach(function(item) {
            !module_list_arr2.includes(item) && module_list_arr2.push(item);
          });
          for (let k in module_list_arr2) {
            if (module_list_arr2.hasOwnProperty(k)) {
              try {
                that.loadModuleData(module_list_arr2[k]);
              } catch (error) {
                console.log(error);
              }
            }
          }
          that.setData(indexData);
          // let _user_info = wx.getStorageSync('user_info');
          // if (_user_info) {
          //   that.setData({
          //     _user_info,
          //     finished: true,
          //   });
          // }
        }
      },
      complete: function() {
        wx.stopPullDownRefresh();
        // wx.hideLoading();
        that.setData({
          showTabbar: true,
        });
      },
    });
    
  },

  loadModuleData(name) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.index_new,
      data: {
        type: name,
        shop_id: 0
      },
      success: function(res) {
        if (res.code === 0) {
          let moduleData = res.data;
          if (name === 'banner') {
            let bannerList = moduleData.banner_list;
            app.wxAppParams(bannerList, 'page_url');
          } else if (name === 'nav') {
            let { nav_icon_list, nav_count: navPerLine } = res.data;

            let navPerGroup = (Number(navPerLine) === 0 ? 4 : 5) * 2;
            let groupCount = Math.ceil(nav_icon_list.length / navPerGroup);
            let navArray = Array.from({ length: groupCount }, (v, i) =>
              nav_icon_list.slice(
                i * navPerGroup,
                i * navPerGroup + navPerGroup
              )
            );
            that.setData({
              navArray,
              navPerLine: navPerLine || 0,
            });
          } else if (name === 'block') {
            let blockList = moduleData.block_list;
            if (blockList.length > 0) {
              for (let i in blockList) {
                if (Object.prototype.hasOwnProperty.call(blockList, i)) {
                  let magicList = blockList[i].data.pic_list;
                  app.wxAppParams(magicList, 'url');
                }
              }
            }
          } else if (name === 'miaosha') {
            that.setData({ miaosha: res.data.goods_list });
          } else if (name === 'notice') {
            that.setData({
              notice: res.data.notice,
              notice_style: res.data.style,
            });
          } else if (name === 'pintuan') {
            that.setData({ pintuan: res.data.goods_list });
          } else if (name === 'goods_list') {
            that.setData({
              rem_list: res.data.list,
              rem_name: res.data.list_name,
            });
          } else if (name === 'shop_list') {
            that.setData({ list_type: 'shops' });
            that.getLocation();
          } else if (name === 'video') {
            that.setData({ update_list: res.data.update_list });
          }
          that.setData(moduleData);
        } else {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
          });
        }
      },
    });
  },

  play(e) {
    this.setData({
      play: e.currentTarget.dataset.index,
    });
  },

  onFullScreen(e) {
    if (e.detail.direction === 'horizontal') {
      this.setData({
        noScrollListen: true,
      });
    } else {
      this.setData({
        noScrollListen: false,
      });
    }
  },

  // 获取分类和导航列表
  loadStoreType() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.storecate,
      data: {
        shop_id: 0
      },
      success: res => {
        if (res.code === 0) {
          let storeInfo = res.data.store_info;
          that.setData({
            storeInfo,
          });
        }
      },
    });
  },

  loadOneStore(default_index, shop_id) {
    let that = this;
    let userLocation = wx.getStorageSync('userLocation');
    _switch = Number(default_index);
    if (_switch === 0) {
      // 跳转至上次浏览门店
      let latestShopId = wx.getStorageSync('latestShopId');
      if (latestShopId) {
        app.ws_micro_shop_globalData.shopid = latestShopId;
        app.ws_micro_shop_globalData.fromHome = false;
        app.util.navigateTo('/ws_micro_shop/pages/index/index');
        return;
      } else {
        that.autoLocation(userLocation);
      }
    } else if ( _switch === 1 && shop_id && firstEntry ) {
      // 跳转至最近门店
      app.ws_micro_shop_globalData.shopid = shop_id;
      firstEntry = false;
      app.ws_micro_shop_globalData.fromHome = false;
      app.util.navigateTo('/ws_micro_shop/pages/index/index');
      return;
    } else {
      // 未设置跳转
      that.autoLocation(userLocation);

      return false;
    }
  },
  autoLocation(e) {
    app.ws_micro_shoprequest({
      url: api.default.coornate,
      data: {
        longitude: e.longitude,
        latitude: e.latitude,
        shop_id: 0
      },
      success: res => {
        if (res.code === 0) {
          if (res.data && res.data.coornate) {
            let coornate = res.data.coornate;
            let { isSearchShow } = this.data;
            let choosedLocation = isSearchShow ? [
              coornate.province,
              coornate.city,
              coornate.district,
            ] : '';
            let choosedArea = isSearchShow ? coornate.district : '全国';
            this.setData({ 
              choosedLocation, 
              choosedArea, 
              sort: 1,
              'param.cate': 2,
              'param.descending': true,
            }, () => {
              this.getStoreList({
                userLng: e.longitude,
                userLat: e.latitude,
                sort: 1,
                distance: 0,
                dir: true,
              });
            });
          }
        }
      },
    });
  },

  // 支持后台自定义跳转
  linkStoreList(e) {
    let { name, id, item } = e.currentTarget.dataset;
    // app.ws_micro_shop_globalData.shopid = 0;
    item.custom ||
      app.util.navigateTo('ws_micro_shop/pages/storelist/index', { id, name }); // 门店分类导航
    item.custom && this.customNavigate(item); // 自定义导航
  },

  customNavigate(nav) {
    let {
      open_type: openType,
      appData = {},
      url,
      out_url: param = '',
      shop_id = 0,
    } = nav;
    shop_id && (app.ws_micro_shop_globalData.shopid = shop_id);

    // 跳转路径处理
    if (openType === 'navigate') {
      let new_url = '';
      if (url.indexOf('/book/') > 0) {
        new_url = '/ws_micro_shop_book' + url;
      } else if (url.indexOf('/pt/') > 0) {
        new_url = '/ws_micro_shop_pt' + url;
      } else if (url.indexOf('/miaosha/') > 0) {
        new_url = '/ws_micro_shop_ms' + url;
      } else if (url.indexOf('_seller/') > 0) {
        new_url = '/' + url;
      } else {
        new_url = '/ws_micro_shop' + url;
      }
      app.ws_micro_shop_navigate({ url: new_url });
    }
    openType === 'module' && app.ws_micro_shop_navigate({ url });
    openType === 'webview' &&
      app.util.navigateTo('ws_micro_shop/pages/web/web', { url: param });
    openType === 'wxapp' &&
      wx.navigateToMiniProgram({
        appId: appData.appId || '',
        path: appData.path || '',
      });
  },

  onPullDownRefresh() {
    let that = this;
    let name = that.data.list_type;
    if (String(name) === 'shops') {
      that.setData({
        shoplist: [],
        page: 1,
        more: true,
        keyword: '',
        hideBtn: true,
      });
      wx.getSetting({
        success(res) {
          if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
            that.getLocation();
          } else if (res.authSetting['scope.userLocation'] === false) {
            that.loadStoreList('', '', 0, 0);
            that.setData({
              open_setting: true,
            });
          } else {
            that.getLocation();
          }
        },
      });
    } else {
      wx.stopPullDownRefresh();
    }
  },

  onReachBottom() {
    let name = this.data.list_type;
    if (String(name) === 'shops') {
      this.getLocation();
    }
  },

  onShareAppMessage() {
    let user_info = wx.getStorageSync('user_info');
    let store =this.data.store;
    return {
      path: '/ws_micro_shop/pages/home/index?user_id=' + user_info.id,
      title: store.name,
    };
  },

  onShareTimeline() {
    let user_info = wx.getStorageSync('user_info');
    let store = this.data.store;
    return {
      title: store.name,
      imageUrl: '',
      query: 'user_id=' + user_info.id
    }
  },

  loadStoreHomeData() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.storehome,
      data: {
        shop_id: 0,
      },
      success: res => {
        if (res.code === 0) {
          app.wxAppParams(res.data.slide, 'page_url');
          that.setData(res.data);
        }
      },
    });
  },

  loadStoreList(lng, lat, sort, distance) {
    let that = this;
    let { shoplist, param, page, keyword, more, list_type, dir } = this.data;
    if (String(list_type) !== 'shops') return;
 
    // #兼容门店列表新增首页的排序 0:综合升序   1:距离升序  2:添加时间降序  3:销量升序  4:综合降序  5:距离降序  6:销量降序  cd 2020-1-8
    if (param.cate === '0') { // 0:综合升序  4:综合降序
      sort = dir ? 4 : 0;
    } else if (param.cate === '1') { // 3:销量升序 6:销量降序
      sort = dir ? 6 : 3;
    } else if (param.cate === '2') {// 1:距离升序 5:距离降序 
      sort = dir ? 5 : 1;
    }

    if (more) {
      app.ws_micro_shoprequest({
        url: api.default.index_new,
        data: {
          type: 'shop_list',
          longitude: lng,
          latitude: lat,
          page,
          keyword,
          sort,
          distance,
          address: that.data.choosedLocation,
          shop_id: 0
        },
        success: res => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          if (res.code === 0) {
            let list = res.data.list;
            if (list && list.length > 0) {
              page += 1;
              that.setData({
                shoplist: shoplist.concat(list),
                page,
                recommended_stores:
                  res.data.recommended_stores_alias || '推荐门店',
              });
            } else {
              // wx.showToast({
              //   title: '没有更多店铺了',
              // });
              that.setData({
                more: false,
              });
            }
          }
        },
      });
    }
  },

  getLocation() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          that.chooseLocation();
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({ dir: true });
          that.loadStoreList('', '', 0, 0);
        } else {
          that.chooseLocation();
        }
      },
    });
  },

  chooseLocation() {
    let that = this;
    wx.getLocation({
      success: function(e) {
        if (e.errMsg !== 'getLocation:ok') {
          return;
        }
        // that.entryNearStore(e.longitude, e.latitude);
        that.loadStoreList(e.longitude, e.latitude, that.data.sort, '');
        that.setData({
          userLat: e.latitude,
          userLng: e.longitude,
        });
      },
      fail: function() {
        that.setData({ dir: true });
        that.loadStoreList('', '', 0, 0);
      },
    });
  },

  toNoticeDetail(e) {
    app.util.navigateTo(
      '/ws_micro_shop/pages/article-detail/article-detail',
      { id: e.currentTarget.dataset.id, type: 'notice' },
      false
    );
  },

  toShopHome(e) {
    let shopid = e.currentTarget.dataset.sid;
    app.ws_micro_shop_globalData.shopid = shopid;
    app.ws_micro_shop_globalData.fromHome = false;
    app.util.navigateTo('/ws_micro_shop/pages/index/index', {}, true);
  },

  applyEnter() {
    app.util.navigateTo('/ws_micro_shop/pages/applyEntry/index', {}, false);
  },

  getUserInfo(e) {
    if (e.detail.userinfo) {
      app.util.navigateTo('/ws_micro_shop/pages/applyEntry/index', {}, false);
    }
  },

  getKeyword(e) {
    let keyword = e.detail.value.trim();
    if (keyword) {
      this.setData({
        hideBtn: false,
      });
    } else {
      this.setData({
        hideBtn: true,
      });
    }
    this.setData({
      keyword,
    });
  },

  search() {
    if (Number(this.data._type) === 1) {
      this.setData({
        shoplist: [],
        page: 1,
        more: true,
      });
      this.getLocation();
    } else {
      app.ws_micro_shop_globalData.shopid = 0;
      app.util.navigateTo(
        '/ws_micro_shop/pages/search/search',
        { keyword: this.data.keyword },
        false
      );
    }
  },

  onNavigate(e) {
    let param = e.currentTarget.dataset;
    let open_type = param.open_type;
    let pageUrl = param.url ? param.url : '';
    if (open_type !== 'wxapp') {
      app.ws_micro_shop_navigate(param);
      return;
    } else {
      let url = app.parseQueryString(pageUrl);
      url.path = url.path ? decodeURIComponent(url.path) : '';
      wx.navigateToMiniProgram({
        appId: url.appId,
        path: url.path,
      });
      return false;
    }
  },

  showSearchType() {
    this.setData({
      showtype: true,
    });
  },

  selectSearchType(e) {
    let type = e.currentTarget.dataset.type;
    if (Number(type) === 1) {
      this.setData({
        _type: type,
        _typename: '门店',
        showtype: false,
      });
    } else if (Number(type) === 2) {
      this.setData({
        _type: type,
        _typename: '商品',
        showtype: false,
      });
    }
  },

  filtrateStore(e) {
    let { cate: index, sort } = e.currentTarget.dataset;
    let {
      param: { cate, descending },
      userLat,
      userLng,
    } = this.data;
    let dir = cate === index ? !descending : true;
    this.setData({
      'param.cate': index,
      'param.descending': cate === index ? !descending : true,
      sort,
      more: true,
      dir,
    });
    this.getStoreList({ userLng, userLat, sort, distance: 0, dir });
  },

  getStoreList({ userLng, userLat, sort, distance, dir } = {}) {
    // #兼容门店列表新增首页的排序 0:综合升序   1:距离升序  2:添加时间降序  3:销量升序  4:综合降序  5:距离降序  6:销量降序  cd 2020-1-8
    let { choosedLocation: address = '', param } = this.data;

    if (param.cate === '0') { // 0:综合升序  4:综合降序
      sort = dir ? 4 : 0;
    } else if (param.cate === '1') { // 3:销量升序 6:销量降序
      sort = dir ? 6 : 3;
    } else if (param.cate === '2') {// 1:距离升序 5:距离降序 
      sort = dir ? 5 : 1;
    }

    app.ws_micro_shoprequest({
      url: api.default.index_new,
      data: {
        type: 'shop_list',
        longitude: userLng,
        latitude: userLat,
        page: 1,
        sort,
        distance,
        address,
        shop_id: 0
      },
      success: res => {
        if (res.code === 0) {
          let shoplist = res.data.list;
          this.setData({
            shoplist,
            page: 2,
          });
          // address && shoplist.length === 0 && wx.showModal({
          //   title: '提示',
          //   content: '所选区域没有相关门店，继续显示所有门店',
          //   showCancel: false,
          //   success: res => {
          //     this.setData({ choosedLocation: '', choosedArea: '全国' }, () => {
          //       res.confirm && this.getStoreList({ userLng, userLat, sort, distance, dir });
          //     });
          //   },
          // });
          address &&
            shoplist.length === 0 &&
            this.setData({ choosedLocation: '', choosedArea: '全国' }, () => {
              this.getStoreList({ userLng, userLat, sort, distance, dir });
            });
        }
      },
    });
  },

  checkAllCate() {
    app.util.navigateTo('ws_micro_shop/pages/storelist/index', {
      name: '全部',
      id: 0,
    });
  },

  homeNavigation(e) {
    app.ws_micro_shop_globalData.fromHome = true;
    let url =
      e.currentTarget.dataset.type === 'cart'
        ? this.data.isBrand
          ? 'ws_micro_shop/pages/storelist/index'
          : 'ws_micro_shop/pages/cart/cart'
        : 'ws_micro_shop/pages/user/user';
    let params = this.data.isBrand ? { name: '全部', id: 0 } : {};
    app.util.navigateTo(url, params, true);
  },

  onChooseLocation(e) {
    let { value = [] } = e.detail;
    value.length > 0 && (value = value.map(v => (v === '全部' ? '' : v))); // “全部”改为传空值
    value.every(v => v === '') && (value = ''); // 都是空值，传一个空值。
    let choosedLocation = value;
    let choosedArea = !value
      ? '全国'
      : value.filter(v => v !== '').reverse()[0];
    let { userLat, userLng } = this.data;

    this.setData({ 
      choosedLocation, 
      choosedArea, 
      sort: 1,
      'param.cate': 2,
      'param.descending': true,
     }, () => {
      this.getStoreList({ userLng, userLat, sort: 1, distance: 0, dir: true });
    });
  },

  showNoticeList() {
    let params = {
      from: 'store',
    };
    app.util.navigateTo('/ws_micro_shop/pages/notice-list/index', params);
  },

  gotoGoodsDetail(e) {
    let dataset = e.currentTarget.dataset;
    app.ws_micro_shop_globalData.shopid = dataset.shop_id;
  }
});
